﻿using Dapper;
using Microsoft.Extensions.Hosting;
using ThresholdAssistant.Dapper.Mappers;
using System;
using System.Linq;
using System.Reflection;

namespace ThresholdAssistant.Dapper.Extensions
{
    /// <summary>
    /// 字段映射工具类
    /// </summary>
    public static class ColumnMapperExtensions
    {
        /// <summary>
        /// 使用Dapper字段映射
        /// </summary>
        /// <param name="builder"></param>
        /// <param name="assemblyNameList">命名空间名称列表</param>
        public static IHostBuilder UseColumnMap(this IHostBuilder builder, params string[] assemblyNameList)
        {
            if (assemblyNameList == null || !assemblyNameList.Any())
                throw new ArgumentNullException("assemblyNameList");

            var assemblyTypeList = assemblyNameList.Select(assemblyName => GetAssembly(assemblyName)).Where(e => e != null).SelectMany(e => e.GetTypes()).Distinct().ToList();
            if (assemblyTypeList != null && !assemblyTypeList.Any())
                return builder;

            assemblyTypeList.ForEach(type => SqlMapper.SetTypeMap(type, new ColumnTypeMapper(type)));
            return builder;
        }

        /// <summary>
        /// 获取程序集
        /// </summary>
        /// <param name="assemblyName"></param>
        private static Assembly GetAssembly(string assemblyName)
        {
            Assembly assembly = null;
            try
            {
                assembly = Assembly.Load(assemblyName);
            }
            catch (Exception)
            {

            }
            return assembly;
        }
    }
}